package com.vWare.documentparser.Controls;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;

public class ListTextView extends TextView 

{

	Paint pText = new Paint();
	String TextToPrint;
	
	 public ListTextView(Context context, AttributeSet attrs, int defStyle) 
	 {
	        super(context, attrs, defStyle);
	 }

	 public ListTextView(Context context, AttributeSet attrs) 
	 {
	       super(context, attrs);
	 }

	 public ListTextView(Context context) 
	 {
	 	 super(context);
	 }
	 
	 

	
	@Override
	protected void onDraw(Canvas canvas)
	{
		
		
		String txtToFormat = super.getText().toString();
		
	//	super.setPadding(super.getPaddingLeft(), super.getPaddingTop(), super.getPaddingRight(), super.getPaddingBottom());
		
		pText.setTextSize(super.getTextSize());
		pText.setAntiAlias(true);
						
		int iLineY = 20;
		float iLineX = 0;
		float iStrWidth = 0;

		String[] txtSplited;
		String txtToPrint = "";
		String txtToPrintWOS = "";
		
		txtSplited = txtToFormat.split(" ");
				
		for (int i = 0; i < txtToFormat.split(" ").length; ++i)
		{
		
			txtToPrintWOS  = txtToPrint.replace(" ", "");
						
			if (DoPrint(txtToPrint  + txtSplited[i]) > super.getWidth()) 
			{
				
				iStrWidth = pText.measureText(txtToPrintWOS);
				
				float SpaceSize = (float) (((super.getWidth() - iStrWidth - this.getPaddingLeft() - this.getPaddingRight()) / (txtToPrint.split(" ").length + 1)) - 0.5);
				
				for (int iST = 0; iST < txtToPrint.split(" ").length; ++iST)
				{
					canvas.drawText(txtToPrint.split(" ")[iST], 0, txtToPrint.split(" ")[iST].length(), iLineX, iLineY, pText);
					iLineX += pText.measureText(txtToPrint.split(" ")[iST]) + SpaceSize;
									
				}
				txtToPrint = "";
				txtToPrint = txtToPrint + " " + txtSplited[i];
				iLineY += 20;
				iLineX = 0;
				
			}
			else if (txtSplited[i].equals("\n"))
			{
				txtToPrint = txtToPrint.trim();
				canvas.drawText(txtToPrint, 0, iLineY, pText);
				txtToPrint = "";
				iLineY += 40;
			}
			else
			{
			txtToPrint = txtToPrint + " " + txtSplited[i];
			txtToPrint = txtToPrint.trim();
			}
		
		}
		
		if (txtToPrint.length() != 0)
		{
			txtToPrint = txtToPrint.trim();
			canvas.drawText(txtToPrint, 0, iLineY, pText);
			txtToPrint = "";
			iLineY += 20;
		//	TextToPrint = txtToPrint;
			this.setHeight(iLineY);
		}
		
		
			
	}
	
	private float DoPrint(String input)
	{
	
		
		String txtInputWOS = input.replace(" ", "");
		float fStrWidthWOS = this.getPaint().measureText(txtInputWOS);
		float fSpaceSize = (super.getWidth() - fStrWidthWOS - super.getPaddingLeft() - super.getPaddingRight()) / (input.split(" ").length);
		
		if (fSpaceSize < 5)
		{
			fSpaceSize += 1;
		}
		
		return (fStrWidthWOS + (input.split(" ").length ) * fSpaceSize);
		
		
	}
	
}